Faker::Config.locale = 'zh-CN'

ADDRESS_LIST = [
  ['广东省', '深圳市', '南山区'],
  ['广东省', '深圳市', '宝安区'],
  ['广东省', '深圳市', '福田区'],
  ['广东省', '深圳市', '罗湖区']
]

def generate_params
  province, city, district = ADDRESS_LIST[rand(ADDRESS_LIST.size)]
  restaurant_params = {
    # uid: UUIDTools::UUID.random_create.to_s,
    name: Faker::Name.name + "饭店",
    province: province,
    city: city,
    district: district,
    address: Faker::Address.street_address,
    longitude: Faker::Address.longitude,
    latitude: Faker::Address.latitude,
    # status: 'enabled',
    max_spec: 0,
  }

  # require_relative()
  table_params = (rand(10) + 2).times.map do
    {
      spec: rand(10) + 1,
      number: rand(5) + 1
    }
  end
  restaurant_params[:max_spec] = table_params.max_by{|table| table[:spec]}[:spec]

  work_params = [
    {
      work_time: {
        status: 'open',
        name: Faker::Name.name
      },
      rules: [
        {
          type: 'TimeRule::Week',
          value: [0,1,2,3,4]        # 周一到周五
        },
        {
          type: 'TimeRule::TimeSlot',
          value: [10.hours.to_i, 22.hours.to_i]     # 10:00 - 22:00
        }
      ]
    },
    {
      work_time: {
        status: 'closed',
        name: Faker::Name.name
      },
      rules: [
        {
          type: 'TimeRule::Week',
          value: [0,1,2]
        },
        {
          type: 'TimeRule::TimeSlot',
          value: [14.hours.to_i, 17.hours.to_i]     # 14:00 - 17:00
        }
      ]
    }
  ]
  [restaurant_params, table_params, work_params]
end

def init_data
  10.times do
    begin
      restaurant_params, table_params, work_params = generate_params

      ApplicationRecord.transaction do
        restaurant = Restaurant.create!(restaurant_params)
        restaurant.dining_tables.create! table_params
        work_params.each do |tmp_params|
          work_time = restaurant.work_times.create! tmp_params[:work_time]
          rules = work_time.time_rules.create! tmp_params[:rules]
        end
      end
    rescue => e
      Rails.logger.error e
      raise
    end
  end
end

def clear_data
  Reservation.destroy_all
  TimeRule.destroy_all
  WorkTime.destroy_all
  DiningTable.destroy_all
  Restaurant.destroy_all
end

def main
  clear_data
  init_data
end

main
